async function pingDomain(domain: string) {
	const startTime = performance.now();
	try {
		if (!domain.startsWith('http')) domain = window.location.origin + domain;
		await fetch(domain, { method: 'HEAD', mode: 'no-cors' });
		const endTime = performance.now();
		return { domain, offset: endTime - startTime };
	} catch (err) {
		console.error(`error pinging ${domain}:`, err);
		return { domain, offset: Infinity };
	}
}

export async function pingAndCompare(domains: string[]) {
	const responses = await Promise.all(domains.map((domain) => pingDomain(domain)));

	const minOffset = Math.min(...responses.map((response) => response.offset));
	const firstResponse = responses.find((response) => response.offset === minOffset)!;

	const { domain, offset: time } = firstResponse;
	console.log(`Fastest domain: ${domain} with time: ${time} ms`);

	return domain;
}
